import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: '',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Content-Type'] ="multipart/form-data"
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.Code !== 1) {
      if (res.Code === 999) {
        // to re-login
        MessageBox.confirm('请重新登录', '登录过期', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: '提示'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.Code === 998) {
        Message({
          message: res.Msg || '无应用可操作',
          type: 'error',
          duration: 5 * 1000
        })
      } else if (res.Code === 997) {
        // Message({
        //   message: res.Msg || '无应用权限',
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        router.replace({
          path: '/noauth'
        })
      } else if (res.Code === 996) {
        router.replace({
          path: '/verify',
          query: { redirect: router.currentRoute.fullPath }
        })
      } else if (res.Code === 995) {
        Message({
          message: res.Msg,
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        Message({
          message: res.Msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(res.Msg)
    } else {
      return res
    }
  },
  error => {
    console.log(error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
